package cn.mayaslight.common.springbean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import cn.mayaslight.common.cache.ICache;
import cn.mayaslight.common.exception.HandleException;
import cn.mayaslight.common.utils.SyncUtils;

@Component
public class CacheManager {

	private static CacheManager instance = null;

	private static Object LOCK = new Object();

	private Set<ICache<?>> caches = new HashSet<ICache<?>>(0);
	
	public void reflesh(String cacheClassName){
		if(StringUtils.isBlank(cacheClassName)){
			throw new HandleException("缓存名字为null!");
		}
		for(Iterator<ICache<?>> it=caches.iterator(); it.hasNext(); ){
			ICache<?> cache = it.next();
			if(cacheClassName.equals(cache.getClass().getName())){
				cache.refresh();
				break;
			}
		}
	}
	
	public List<String> listAllCacheClass () {
		List<String> names = new ArrayList<String>();
		if(caches != null && !caches.isEmpty()){
			for(Iterator<ICache<?>> it = caches.iterator(); it.hasNext(); ){
				ICache<?> cache = it.next();
				String cacheClassName = cache.getClass().getName();
				names.add(cacheClassName);
			}
		}
		Collections.sort(names);
		return names;
	}
	
	public void refresh() {
		if(caches != null && !caches.isEmpty()){
			for(Iterator<ICache<?>> it = caches.iterator(); it.hasNext(); ){
				ICache<?> cache = it.next();
				cache.refresh();
			}
		}
	}

	@Resource
	private RedisTemplate<String, List<?>> redisTemplate;

	private CacheManager() {

	}

	@PostConstruct
	public void init() {
		instance = this;
	}

	public static CacheManager getInstance() {
		instance = SyncUtils.sync(instance, CacheManager.class, LOCK);
		return instance;
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> loadByKey(Class<? extends ICache<T>> clazz, String key) {
		List<T> list = (List<T>) getInstance().getRedisTemplate().opsForValue().get(clazz.getName() + "@@" + key);
		return list;
	}

	public static <T> T loadUniqueByKey(Class<? extends ICache<T>> clazz, String key) {
		List<T> listData = loadByKey(clazz, key);
		if(listData == null || listData.isEmpty()){
			return null;
		}else{
			return listData.get(0);
		}
	}

	public RedisTemplate<String, List<?>> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, List<?>> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

}
